package com.chezai.client.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Camera.Face;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.chezai.client.R;
import com.chezai.client.global.Const;
import com.chezai.client.global.TerminalApplication;


public class FaceView extends AppCompatImageView {
    public static final int FACE_DETECT_GOOD = 0X0001;
    public static final int FACE_DETECT_LEFT = 0X0002;
    public static final int FACE_DETECT_RIGHT = 0X0003;
    public static final int FACE_DETECT_TOP = 0X0004;
    public static final int FACE_DETECT_BOTTOM = 0X0005;
    public static final int FACE_DETECT_OUT = 0X0006;
    private Paint mLinePaint;
    private Face[] mFaces;
    private Matrix mMatrix = new Matrix();
    private RectF mRect = new RectF();
    private Drawable mFaceIndicator = null;
    private boolean isMirror = true;
    private int mDisplayOrientation;
    private Rect mDetectRect;
    private float mDetectArea;

    public FaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
        mContext = context;
        mFaceIndicator = getResources().getDrawable(R.drawable.ic_face_find_2);
    }

    /**
     * 设置是否为镜面
     * 此处加这个型号判断，可能是因为立裕泰的设备，摄像头被修改过，所以不需要mirror
     *
     * @param id
     */
    public void isMirror(int id) {
        if (!Const.C703B.equals(TerminalApplication.channelModel)) {
            if (id == Camera.CameraInfo.CAMERA_FACING_BACK) {
                this.isMirror = false; //后置Camera无需mirror
            } else if (id == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                this.isMirror = true;  //前置Camera需要mirror
            }
        } else {
            this.isMirror = false;
        }
        invalidate();
    }

    /**
     * 设置摄像头旋转角度
     *
     * @param displayOrientation
     */
    public void setDisplayOrientation(int displayOrientation) {
        this.mDisplayOrientation = displayOrientation;
        invalidate();
    }


    public void setFaces(Face[] faces) {
        this.mFaces = faces;
        invalidate();
    }

    public void clearFaces() {
        mFaces = null;
        invalidate();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        if (mFaces == null || mFaces.length < 1) {
            return;
        }
        prepareMatrix(mMatrix, isMirror, mDisplayOrientation, getWidth(), getHeight());
        canvas.save();
        mMatrix.postRotate(0); //Matrix.postRotate默认是顺时针
        canvas.rotate(-0);   //Canvas.rotate()默认是逆时针
        for (int i = 0; i < mFaces.length; i++) {
            mRect.set(mFaces[i].rect);
            mMatrix.mapRect(mRect);
            mFaceIndicator.setBounds(Math.round(mRect.left), Math.round(mRect.top),
                    Math.round(mRect.right), Math.round(mRect.bottom));
            mFaceIndicator.draw(canvas);
//			canvas.drawRect(mRect, mLinePaint);
        }
        canvas.restore();
        super.onDraw(canvas);
    }

    private void initPaint() {
        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//		int color = Color.rgb(0, 150, 255);
        int color = Color.rgb(98, 212, 68);
//		mLinePaint.setColor(Color.RED);
        mLinePaint.setColor(color);
        mLinePaint.setStyle(Style.STROKE);
        mLinePaint.setStrokeWidth(5f);
        mLinePaint.setAlpha(180);
    }

    public RectF getFaceRect(Face face) {
        RectF rectF = new RectF(face.rect);
        prepareMatrix(mMatrix, isMirror, mDisplayOrientation, getWidth(), getHeight());
        mMatrix.postRotate(0);
        mMatrix.mapRect(rectF);
        return rectF;
    }

    public void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
                              int viewWidth, int viewHeight) {
        // Need mirror for front camera.
        matrix.setScale(mirror ? -1 : 1, 1);
        // This is the value for android.hardware.Camera.setDisplayOrientation.
        matrix.postRotate(displayOrientation);
        // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
        // UI coordinates range from (0, 0) to (width, height).
        matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
        matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
    }

    public void setPreviewViewRect(@NonNull Rect faceRoundRect) {
        this.mDetectRect = faceRoundRect;
        this.mDetectArea = area(mDetectRect.width(), mDetectRect.height());
    }

    /**
     * 是否包含
     *
     * @param rectF
     * @return
     */
    public boolean contains(RectF rectF) {
        return mDetectRect.contains(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF.bottom));
    }

    public boolean intersect(RectF rectF) {
        return mDetectRect.intersects(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF.bottom));
    }

    public int compareRect(RectF rectF) {
        if (intersect(rectF)) {//是否与检测区域有交集
            if (contains(rectF)) {//被包含在检测区域内
                return FACE_DETECT_GOOD;
            } else {
                if (mDetectRect.left > rectF.left) {
                    return FACE_DETECT_LEFT;
                }
                if (mDetectRect.top > rectF.top) {
                    return FACE_DETECT_TOP;
                }
                if (mDetectRect.right < rectF.right) {
                    return FACE_DETECT_RIGHT;
                }
                if (mDetectRect.bottom < rectF.bottom) {
                    return FACE_DETECT_BOTTOM;
                }
            }
        }
        return FACE_DETECT_OUT;
    }

    private float area(float w, float h) {
        return w * h;
    }
}
